<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-01-30
 * Time: 16:10:50
 * Info: 管理员模块
 */
defined('IN_YZMPHP') or exit('Access Denied');
yzm_base::load_controller('common', 'admin', 0);
yzm_base::load_model("auth_group_model", "admin");

class admin extends common
{

    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = D('admin');
    }

    public function init()
    {
        if (is_ajax()) {
            $limit = (int)input('limit', 10);
            $page  = (int)input('page', 1);
            $first = ($page - 1) * $limit;
            $field = input('field', 'id');
            $order = input('order', 'asc');
            $key   = input('key');

            //获取用户组
            $authGroup    = D("auth_group")->field("id,name")->select();
            $authGroupIds = array_column($authGroup, null, 'id');

            $where = "1=1";
            if ( ! empty($key['username'])) {
                $where .= " and username = '{$key['username']}'";
            }
            if ( ! empty($key['role_id'])) {
                $where .= " and role_id = '{$key['role_id']}'";
            }
            if (isset($key['status']) && $key['status'] != '') {
                $where .= " and status = '{$key['status']}'";
            }

            $list = $this->model->field("id,username,role_id,nick_name,real_name,email,login_time,login_ip,status,create_time")->where($where)->limit("{$first},{$limit}")->order("{$field} {$order}")->select();
            foreach ($list as $key => $v) {
                $list[$key]['createtime'] = date("Y-m-d H:i:s", $list[$key]['createtime']);
                $list[$key]['login_time'] = date("Y-m-d H:i:s", $list[$key]['login_time']);
                $list[$key]['group_name'] = isset($authGroupIds[$list[$key]['role_id']]['name']) ? $authGroupIds[$list[$key]['role_id']]['name'] : '';
            }

            $count = $this->model->total();
            return_json(['code' => 0, 'msg' => 'ok', 'data' => $list, 'count' => $count]);
        }
        $role_group_name = auth_group_model::getRoleGroup();
        include $this->admin_tpl('admin/index');
    }

    public function add()
    {
        $a = rand_string();
        if (is_post()) {
            $param = input('post.');
            if (empty($param['username'])) {
                return_error("用户名不能为空");
            }
            if (empty($param['nick_name'])) {
                return_error("昵称不能为空");
            }
            if (empty($param['password'])) {
                return_error("密码不能为空");
            }
            if (empty($param['role_id'])) {
                return_error('角色组不能为空');
            }
            if (strlen($param['password']) < 6) {
                return_error('密码长度不能小于6位哦');
            }
            $salt                 = rand_string();
            $param['role_id']     = (int)$param['role_id'];
            $param['status']      = (int)$param['status'];
            $param['username']    = remove_xss($param['username']);
            $param['nick_name']   = remove_xss($param['nick_name']);
            $param['salt']        = $salt;
            $param['password']    = cmf_password(remove_xss($param['password']), $salt);
            $param['email']       = remove_xss($param['email']);
            $param['create_time'] = time();
            $param['update_time'] = time();
            $adminId              = $this->model->insert($param);
            //更新对应角色表
            $this->updateAdminGroup($adminId, $param['role_id']);
            $this->success("保存成功");
        }
        $role_group_name = auth_group_model::getRoleGroup();
        include $this->admin_tpl('admin/add');
    }

    public function edit()
    {
        if (is_post()) {
            $param = input('post.');
            if (empty($param['id'])) {
                return_error('参数错误');
            }
            if (empty($param['username'])) {
                return_error("用户名不能为空");
            }
            if (empty($param['nick_name'])) {
                return_error("昵称不能为空");
            }
            if (empty($param['role_id'])) {
                return_error('角色组不能为空');
            }
            if ( ! empty($param['password'])) {
                if (strlen($param['password']) < 6) {
                    return_error('密码长度不能小于6位哦');
                }
                $salt              = rand_string();
                $param['salt']     = $salt;
                $param['password'] = cmf_password(remove_xss($param['password']), $salt);
            } else {
                unset($param['password']);
            }
            $param['id']          = (int)$param['id'];
            $param['role_id']     = (int)$param['role_id'];
            $param['status']      = (int)$param['status'];
            $param['username']    = remove_xss($param['username']);
            $param['nick_name']   = remove_xss($param['nick_name']);
            $param['email']       = remove_xss($param['email']);
            $param['update_time'] = time();

            $this->model->update($param, ['id' => $param['id']]);
            //更新对应角色表
            $this->updateAdminGroup($param['id'], $param['role_id']);
            return_success("保存成功");
        }
        $id = (int)input('get.id');
        if (empty($id)) {
            showmsg('参数错误', 'stop');
        }
        $data = $this->model->where(['id' => $id])->find();
        if (empty($data)) {
            showmsg('获取数据失败', 'stop');
        }
        $role_group_name = auth_group_model::getRoleGroup();
        include $this->admin_tpl('admin/edit');
    }

    public function delete()
    {
        if (is_post()) {
            $id = (int)input('get.id');
            if (empty($id)) {
                $this->error("参数错误");
            }
            if ($id == 1) {
                $this->error('不允许删除id=1的数据');
            }
            $this->model->delete(['id' => $id]);
            $this->success("删除成功");
        }
    }

    public function status()
    {
        if (is_post()) {
            $id  = (int)input('get.id');
            $val = (int)input('post.val', 1);
            if (empty($id)) {
                $this->error('参数错误');
            }
            if ($id == 1) {
                $this->error('不允许修改id=1的状态');
            }
            $this->model->update(['status' => $val], ['id' => $id]);
            $this->success("更改状态成功");
        }
    }

    //获取用户信息
    public function public_user_info()
    {
        $id = (int)input('get.id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $data = $this->model->where(['id' => $id])->find();
        if (empty($data)) {
            $this->error('获取信息失败');
        }
        include $this->admin_tpl('admin/user_info');
    }

    //直接修改用户头像
    public function public_edit_avatar()
    {
        if (is_post()) {
            $param = input('post.');
        }
        if (empty($param['id'])) {
            $this->error('参数错误');
        }
        $param['update_time'] = time();
        $this->model->update($param, ['id' => $param['id']]);
        $this->success('保存成功');
    }

    //修改密码
    public function public_pass()
    {
        if (is_post()) {
            $param = input('post.');
            if (empty($param['oldpwd'])) {
                $this->error('旧密码不能为空');
            }
            if (empty($param['newpwd'])) {
                $this->error('新密码不能为空');
            }
            //查询旧密码是否正确：
            $data = $this->model->where(['id' => $param['id']])->find();
            if ($data['password'] != cmf_password($param['oldpwd'], $data['salt'])) {
                $this->error("旧密码不正确哦");
            }

            $salt                 = rand_string();
            $param['salt']        = $salt;
            $param['password']    = cmf_password($param['newpwd'], $salt);
            $param['update_time'] = time();
            $this->model->update($param, ['id' => $param['id']]);
            $this->success("修改成功");
        }
        $id = input('get.id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $data = $this->model->where(['id' => $id])->find();
        if (empty($data)) {
            $this->error('获取数据失败');
        }
        include $this->admin_tpl('admin/user_pass');
    }

    //更新角色表
    private function updateAdminGroup($adminId, $groupId)
    {
        if (empty($adminId) || empty($groupId)) {
            return;
        }
        //先删除再写入
        D('auth_group_access')->delete(['uid' => $adminId]);
        $data = ['uid' => $adminId, 'group_id' => $groupId];
        D('auth_group_access')->insert($data, false, false);
    }
}
